import { HttpParams } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { httpInterceptorProviders } from 'src/app/api/http-interceptors';
import { RoleApiService } from 'src/app/api/role-api.service';
import { Role } from 'src/app/model/role';

@Component({
  selector: 'app-role',
  templateUrl: './role.component.html',
  styleUrls: ['./role.component.less', '../../../styles/container.css']
})
export class RoleComponent implements OnInit {

  searchForm: FormGroup;
  roleInfoForm: FormGroup;
  roleList: Array<Role>;
  tableLoading = false;
  pageIndex = 1;
  pageSize = 10;
  total = 0;
  isInfoVisible = false;
  inforFormTitle = "添加角色";
  activateStatusLoadingStatus = new Map<number, boolean>()
  constructor(
    private fb: FormBuilder,
    private roleApi: RoleApiService,
    private message: NzMessageService,
    private router: Router,
  ) {
    this.searchForm = this.fb.group({
      keyword: []
    });
    this.roleInfoForm = this.fb.group({
      id: [],
      name: [],
      description: [],
      sort: [],
      status: [],
    })
  }

  ngOnInit(): void {
    this.getListFromServer()
  }

  onSubmit() { this.getListFromServer(); }
  handleAdd() {
    this.inforFormTitle = "添加角色";
    this.isInfoVisible = true;
  }
  handleEdit(data: Role) {
    this.inforFormTitle = "编辑角色";
    this.setFormValue(data);
    this.isInfoVisible = true;
  }
  handlePageIndexChange() { this.getListFromServer(); }
  handlePageSizeChange() { this.getListFromServer(); }
  handleCancel() {
    this.isInfoVisible = false;
    this.roleInfoForm.reset();
  }

  handleModalOk() {
    let id = this.roleInfoForm.controls['id'].value;
    if (id) {
      this.handleEidtRole(id, this.roleInfoForm.value);
    } else {
      this.handleAddRole(this.roleInfoForm.value);
    }
  }
  handleaActivateStatusClick(id: number) { }
  handleAllocMenu(id: number) {
    let url = this.router.parseUrl('/ums/allocMenu');
    url.queryParams = {roleId: id},
    this.router.navigateByUrl(url);
   }
  handleAllocResource(id: number) {
    let url = this.router.parseUrl('/ums/allocResource');
    url.queryParams = {roleId: id},
    this.router.navigateByUrl(url);
   }


  handleDelete(id: number) {
    this.roleApi.delete([id]).subscribe(
      response => {
        this.message.success('删除角色成功');
        this.getListFromServer()
      },
      err => {
        this.message.error('删除角色错误');
        console.error(err);
      }
    )
  }
  cancelDelete() { }
  private getListFromServer() {
    this.tableLoading = true;
    let params = new HttpParams({
      fromObject: {
        'pageNum': this.pageIndex.toString(),
        'pageSize': this.pageSize.toString()
      }
    })
    const keywordValue = this.searchForm.get('keyword')
    if (keywordValue.value) {
      params = params.append('keyword', keywordValue.value)
    }
    this.roleApi.list(params).subscribe(
      response => {
        this.tableLoading = false;
        this.roleList = response.list;
        this.total = response.total,
          console.log(response);
      },
      err => {
        this.message.error('服务器错误');
        this.tableLoading = false;
        console.error('服务器错误');
      }
    )
  }

  private setFormValue(data: Role) {
    for (const key in data) {
      if (Object.prototype.hasOwnProperty.call(data, key)) {
        if (this.roleInfoForm.contains(key)) {
          this.roleInfoForm.controls[key].setValue(data[key])
        }
      }
    }
  }

  private handleAddRole(data: Role) {
    this.roleApi.create(data).subscribe(
      response => {
        this.getListFromServer();
        this.message.success('创建角色成功');
        this.handleCancel();

      },
      err => {
        this.message.error('创建角色错误');
        this.handleCancel();
        console.error(err);

      }
    )
  }

  private handleEidtRole(id: number, data: Role) {
    this.roleApi.update(id, data).subscribe(
      response => {
        this.getListFromServer();
        this.message.success('编辑角色成功');
        this.handleCancel();
      },
      err => {
        this.message.error('编辑角色错误');
        this.handleCancel();
        console.error(err);

      }
    )
  }
}
